package com.atguigu.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.atguigu.dao.TravelGroupDao;
import com.atguigu.pojo.TravelGroup;
import com.atguigu.pojo.TravelItem;
import com.atguigu.service.TravelGroupService;
import com.atguigu.vo.PageResult;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = TravelGroupService.class)
@Transactional
public class TravelGroupServiceImpl implements TravelGroupService {

    @Autowired
    TravelGroupDao travelGroupDao;

    @Override
    public void add(Integer[] travelItemIds, TravelGroup travelGroup) {
        travelGroupDao.add(travelGroup);
        Integer travelGroupId = travelGroup.getId();

        setTravelGroupAndTravelItem(travelGroupId,travelItemIds);
    }

    @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage,pageSize);
        Page page = travelGroupDao.findPage(queryString);

        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public TravelGroup get(Integer id) {
        return travelGroupDao.get(id);
    }

    @Override
    public Integer[] getTravelItemIdByTravelGroupId(Integer id) {

        return travelGroupDao.getTravelItemIdByTravelGroupId(id);
    }

    @Override
    public void update(Integer[] travelItemIds, TravelGroup travelGroup) {
        travelGroupDao.update(travelGroup);

        travelGroupDao.delete(travelGroup.getId());

        setTravelGroupAndTravelItem(travelGroup.getId(),travelItemIds);
    }

    @Override
    public void deleteTravelGroup(Integer id) throws RuntimeException {
        Integer travelItemIdByTravelGroupId = travelGroupDao.TravelItemIdByTravelGroupId(id);
        if (travelItemIdByTravelGroupId > 0 ){
            throw new RuntimeException("有属性绑定");
        }
        travelGroupDao.deleteTravelGroup(id);
    }

    @Override
    public List<TravelGroup> findAll() {
        return travelGroupDao.findAll();
    }


    private void setTravelGroupAndTravelItem(Integer travelGroupId, Integer[] travelItemIds){
        if (travelItemIds != null && travelItemIds.length > 0){
            for (Integer travelItemId : travelItemIds) {
                Map map = new HashMap();
                map.put("travelGroupId",travelGroupId);
                map.put("travelItemId",travelItemId);
                travelGroupDao.setTravelGroupAndTravelItem(map);
            }
        }
    }
}
